package cc.chengheng.dao;

import cc.chengheng.model.PermissionDto;
import cc.chengheng.model.UserDto;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Repository
public class UserDao {

    @Resource
    JdbcTemplate jdbcTemplate = new JdbcTemplate();

    public UserDto getUserByUsername(String username){
        String sql ="SELECT id,username,password,fullname FROM `user_db`.`t_user` where username = '" + username + "'";
        List<UserDto> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(UserDto.class));

        return list.get(0);
    }

    /**
     * 根据用户id查询用户的权限
     */
    public List<String> findPermissionsByUserId(String userId){

        String sql =
                "SELECT * from t_permission where id in(" +
                    "select permission_id from t_role_permission WHERE role_id in (" +
                        "select role_id from t_user_role WHERE user_id = '"+ userId +"'" +
                    ")" +
                ")";

        List<PermissionDto> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(PermissionDto.class));
        List<String> permissions = new ArrayList<>();
        list.forEach((c) -> {
            permissions.add(c.getCode());
        });
        return permissions;
    }

}
